/*
 * @Author: taoyuqing
 * @Date: 2023-01-10 02:32:55
 * @Description: 
 */
import 'dart:convert';
import 'dart:ffi';

import 'package:animated_digit/animated_digit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spree/pages/games/game_manual.dart';
import 'package:spree/pages/games/game_title_bar.dart';
import 'package:spree/pages/games/games_auto.dart';
import 'package:spree/pages/games/games_table.dart';
import 'package:spree/utils/utils.dart';
import 'package:spree/utils/videoUtil.dart';
import 'package:spree/widgets/common_container.dart';
import 'package:spree/widgets/vip_rectangle_box.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import '../../../../provider/model/user_model.dart';
import '../../../../utils/account.dart';
import '../../../../utils/api.dart';
import '../../../../utils/precision_limit_formatter.dart';
import 'mines_array.dart';

class MinesPage extends StatefulWidget {
  MinesPage({Key? key}) : super(key: key);

  @override
  State<MinesPage> createState() => _MinesPageState();
}

class _MinesPageState extends State<MinesPage> with TickerProviderStateMixin {
  List _mines = [];
  late TabController _tabController;
  late TabController _tabController2;
  final List _tabs = ["Manual", "Auto"];
  final List _tabs2 = ["My Bets", "Player List"];
  int _fIndex = 0;
  int _fIndex2 = 0;
  int _bombsNum = 4;
  List _hitList = [];
  late AnimatedDigitController _accountAmountController;
  int hitCount = 0;
  late final IO.Socket _socket = IO.io(
      'http://47.95.0.143:9005',
      IO.OptionBuilder()
          .setPath('/game/socket.io')
          .setTransports(['websocket'])
          .disableAutoConnect()
          .build());
  late String betText = "BET";
  late Color betColor = Color(0xFF7A50F0);
  bool hasClickBet = false;
  List clicks = [];
  bool settle = false;
  bool canCommit = false;
  String cashOutMoney = '';
  List tempList = [];

  late TextEditingController _textEditingController;
  // 表头
  final List<String> _myBetHeader = [
    'Bet ID',
    'Time',
    'Bet',
    'Cash Out',
    'Profit'
  ];
  final List<String> _playerHeader = ['Player', 'Cash Out', 'Bets'];
  // 数据
  List<Map> _myBetData = [];
  List<Map> _playerData = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initGameData();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _tabController2 = TabController(length: _tabs2.length, vsync: this);
    _textEditingController = TextEditingController(text: '1');
    wsConnect(context);
    setState(() {});
    getMyBetsAndAccount();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _tabController.dispose();
    _tabController2.dispose();
    _textEditingController.dispose();
    if (_socket != null) {
      _socket.clearListeners();
      _socket.disconnect();
    }
    super.dispose();
  }

  // 初始化ws
  wsConnect(BuildContext context) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      String? accessToken = context.read<UserModel>().accessToken;
      String? userId = context.read<UserModel>().userId;
      // if (userId == '') {
      //   return;
      // }
      _socket.connect();
      _socket.onConnect((data) async {
        Map gameEnter = {
          'gameType': 'MINES',
        };
        sendMsg('game_enter', gameEnter);
        if (userId != '') {
          Map pre = {
            'userId': userId,
            'gameType': 'MINES',
            'minesCount': _bombsNum
          };
          sendMsg('game_pre', pre);
        }

        _onMessage(userId);
      });
      _socket.onDisconnect((data) {
        print('断开=====');
      });

      // _onMessage(context);
    } catch (e) {
      print(e);
    }
  }

  initGameConfig(bombNum) {
    _hitList = [];
    List tempArray = tempList[bombNum];
    for (int i = 0; i < tempArray.length - 1; i++) {
      if (tempArray[i] != null) {
        double temp = tempArray[i];
        _hitList.add(
            {'labelValue': '$temp', 'clickValue': '$i', 'isSelect': false});
      }
    }

    setState(() {
      _hitList;
    });
  }

  // 监听消息
  _onMessage(String? userId) {
    try {
      _socket.on("game_config", (data) {
        Map result = jsonDecode(data);
        tempList = result['outPut'];
        int bombNum = _bombsNum;
        initGameConfig(bombNum);
      });

      _socket.on('game_pre', (data) {
        Map map = jsonDecode(data);
        //此时说明之前有选中的历史
        if (map['historyClick'] != null) {
          String historyClick = map['historyClick'];
          List<String> historyClicks = historyClick.split(",");
          for (int i = 0; i < historyClicks.length; i++) {
            String click = historyClicks[i];

            _mines[int.parse(click)]['type'] = 3;
          }
          hitCount = historyClicks.length;
          _hitList[hitCount - 1]['isSelect'] = true;
          betText = "CASHOUT";
          betColor = Color.fromRGBO(255, 80, 111, 1);
          hasClickBet = true;
          canCommit = true;
          double mutiplier = double.parse(_hitList[hitCount - 1]['labelValue']);
          double inputMoney = double.parse(_textEditingController.text);
          cashOutMoney = (mutiplier * inputMoney).toString();
          setState(() {});
        }
      });
      _socket.on('game_start', (data) async {
        Map result = jsonDecode(data);
        //这里是结算
        if (settle) {
          List bombs = result['fields'];
          //显示出炸弹
          for (int i = 0; i < bombs.length; i++) {
            _mines[int.parse(bombs[i])]['type'] = 1;
          }
          //显示出已经点击的
          for (int i = 0; i < clicks.length; i++) {
            _mines[clicks[i]]['type'] = 3;
          }
          //显示出原始的
          for (int i = 0; i <= 24; i++) {
            if (_mines[i]['type'] == null || _mines[i]['type'] == 0) {
              _mines[i]['type'] = 4;
            }
          }
          _accountAmountController.addValue(result['winAmount']);
          setState(() {
            betText = "BET";
            betColor = Color(0xFF7A50F0);
            hasClickBet = false;
            canCommit = false;
            settle = false;
            clicks = [];
            _showDialog(false,
                imgSrc: 'images/games/mines/winBackground.png',
                subTitle: 'You Won ' + result['winAmount'].toStringAsFixed(2));
          });
          VideoUtil.playVideoByUrl("sounds/mines/mines-win.mp3");
          String? userId = context.read<UserModel>().userId;
          getMyBets();
          Map pre = {
            'userId': userId,
            'gameType': 'MINES',
            'minesCount': _bombsNum
          };
          sendMsg('game_pre', pre);
        } else {
          //这个时候翻到了金币
          if (result['win']) {
            canCommit = true;
            //上一次点击的转成点击的金币
            _mines[clicks[clicks.length - 1]]['type'] = 3;
            hitCount++;
            //回退上一个的选中状态
            if (hitCount >= 2) {
              _hitList[hitCount - 2]['isSelect'] = false;
            }
            _hitList[hitCount - 1]['isSelect'] = true;
            if (hitCount >= 1) {
              betColor = Color.fromRGBO(255, 80, 111, 1);
            }
            double mutiplier =
                double.parse(_hitList[hitCount - 1]['labelValue']);
            double inputMoney = double.parse(_textEditingController.text);
            cashOutMoney = (mutiplier * inputMoney).toString();
            setState(() {});
            VideoUtil.playVideoByUrl("sounds/mines/mines-match.mp3");
          } else {
            //翻到了炸弹
            List bombs = result['fields'];
            //显示出炸弹
            for (int i = 0; i < bombs.length; i++) {
              setState(() {
                _mines[int.parse(bombs[i])]['type'] = 1;
              });
            }
            //显示出已经点击的
            for (int i = 0; i < clicks.length - 1; i++) {
              setState(() {
                _mines[clicks[i]]['type'] = 3;
              });
            }
            setState(() {
              _mines[clicks[clicks.length - 1]]['type'] = 5;
            });
            //显示出原始的
            for (int i = 0; i <= 24; i++) {
              if (_mines[i]['type'] == null || _mines[i]['type'] == 0) {
                setState(() {
                  _mines[i]['type'] = 4;
                });
              }
            }
            double inputMoney = double.parse(_textEditingController.text);
            _accountAmountController.addValue(-inputMoney);
            setState(() {
              betText = "BET";
              betColor = Color(0xFF7A50F0);
              hasClickBet = false;
              canCommit = false;
              clicks = [];
              //还原布
            });
            String loseMoney = _textEditingController.text;
            _showDialog(true,
                imgSrc: 'images/games/mines/loseBackground.png',
                subTitle: 'You Lose $loseMoney x');
            String? userId = context.read<UserModel>().userId;
            VideoUtil.playVideoByUrl("sounds/mines/mines-lose.mp3");
            Map pre = {
              'userId': userId,
              'gameType': 'MINES',
              'minesCount': _bombsNum
            };
            sendMsg('game_pre', pre);
          }
        }
      });
      _socket.on("game_bet", ((data) {
        Map result = jsonDecode(data);
        print(data);
        if (result['success']) {
          hasClickBet = true;
          changeBetToCashOut();
        } else {
          String errorMsg = result['errorMsg'];
          hasClickBet = false;
          _showChargeAlert(errorMsg);
        }
      }));
      _socket.on("game_real_time_mines", ((data) {
        List result = jsonDecode(data);
        _playerData = [];
        if (result.length > 0) {
          for (int i = 0; i < result.length; i++) {
            _playerData.add({
              'player': result[i]['userName'],
              'cashOut': result[i]['mutiplier'].toString() + 'x',
              'bets': result[i]['betAmount'],
              'win': result[i]['win']
            });
          }
        }
      }));
    } catch (e) {
      print(e);
    }
  }

  // 发送消息
  sendMsg(msg, prama) {
    print(prama);
    try {
      _socket.emit(msg, prama);
    } catch (e) {}
  }

  // 断开连接
  disConnect() {
    try {
      _socket.onDisconnect((data) {});
    } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SvgPicture.asset('images/BETSPREELOGO.svg'),
              Consumer<UserModel>(builder: (context, value, child) {
                return _circleMoney();
              })
            ],
          ),
        ),
        body: Consumer<UserModel>(builder: (context, value, child) {
          return CommonContainer(
            child: ListView(
              children: [
                GameTitleBar(
                  gameName: 'Mines',
                  ontap: (type) {
                    if (type == 'info') {
                      Navigator.pushNamed(context, 'MinesRules');
                    }
                  },
                ),
                Container(
                  height: 400,
                  decoration: BoxDecoration(
                    color: Color(0xFF292158),
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  ),
                  child: Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                        child: Row(
                          children: [
                            Expanded(
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: [
                                  Text(
                                    'COINS',
                                    style:
                                        TextStyle(color: Utils().whiteColor()),
                                  ),
                                  Image.asset(
                                    'images/games/mines/coin.png',
                                    width: 25,
                                  ),
                                  Text(
                                    '${25 - _bombsNum}',
                                    style:
                                        TextStyle(color: Utils().whiteColor()),
                                  )
                                ],
                              ),
                              flex: 1,
                            ),
                            Container(
                              height: 30,
                              width: 1,
                              color: Color(0xFF6145FF),
                            ),
                            Expanded(
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: [
                                  Text(
                                    'BOMBS',
                                    style:
                                        TextStyle(color: Utils().whiteColor()),
                                  ),
                                  Image.asset(
                                    'images/games/mines/bomb.png',
                                    width: 25,
                                  ),
                                  Text(
                                    '$_bombsNum',
                                    style:
                                        TextStyle(color: Utils().whiteColor()),
                                  )
                                ],
                              ),
                              flex: 1,
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: GridView(
                            padding: EdgeInsets.only(left: 10, right: 10),
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                                    mainAxisSpacing: 6,
                                    crossAxisSpacing: 6,
                                    crossAxisCount: 5, //横轴三个子widget
                                    childAspectRatio: 50 / 40 //宽高比为1时，子widget
                                    ),
                            children: _mines
                                .asMap()
                                .keys
                                .map((i) => GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          if (_mines[i]['type'] != null &&
                                              _mines[i]['type'] != 0) {
                                            return;
                                          }
                                          ;
                                          VideoUtil.playVideoByUrl(
                                              "sounds/mines/mines-click.mp3");
                                          if (!hasClickBet) {
                                            EasyLoading.showToast(
                                                'please click Bet');
                                            return;
                                          }
                                          clicks.add(i);

                                          gameStart(i, value.userId);
                                        });

                                        ;
                                      },
                                      child: _gameDatas(_mines[i]['type']),
                                    ))
                                .toList()),
                        flex: 1,
                      ),
                      Container(
                        height: 50,
                        margin: EdgeInsets.only(top: 12),
                        child: ListView(
                          scrollDirection: Axis.horizontal,
                          padding: EdgeInsets.only(bottom: 20),
                          children: _hitList
                              .asMap()
                              .keys
                              .map((i) => _hit(
                                  text: _hitList[i]['labelValue'],
                                  text2: _hitList[i]['clickValue'],
                                  isSelect: _hitList[i]['isSelect']))
                              .toList(),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 20),
                  child: Row(
                    children: [
                      Expanded(
                        child: Container(
                          height: 80,
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(
                              left: 10, right: 10, top: 6, bottom: 6),
                          decoration: BoxDecoration(
                            border: _loutLine(),
                            borderRadius:
                                const BorderRadius.all(Radius.circular(10.0)),
                          ),
                          child: Row(
                            children: [
                              Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  _minButton(
                                      ontap: () {
                                        setState(() {
                                          if (hasClickBet) {
                                            return;
                                          }
                                          _textEditingController.text = '0';
                                        });
                                      },
                                      child: Text(
                                        'Min',
                                        style: TextStyle(color: _whiteColor()),
                                      )),
                                  _minButton(
                                      ontap: () {
                                        setState(() {
                                          if (hasClickBet) {
                                            return;
                                          }
                                          _textEditingController.text = '1000';
                                        });
                                      },
                                      child: Text(
                                        'Max',
                                        style: TextStyle(color: _whiteColor()),
                                      ))
                                ],
                              ),
                              Expanded(
                                child: Padding(
                                  padding: EdgeInsets.only(left: 10, right: 10),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(
                                        'R\$',
                                        style: TextStyle(
                                            color: _whiteColor(),
                                            fontWeight: FontWeight.w800),
                                      ),
                                      TextField(
                                        textAlign: TextAlign.center,
                                        keyboardType: TextInputType.number,
                                        inputFormatters: [
                                          // FilteringTextInputFormatter.allow(
                                          //     RegExp("[0-9]"))
                                          PrecisionLimitFormatter(2)
                                        ],
                                        readOnly: hasClickBet,
                                        controller: _textEditingController,
                                        style: TextStyle(color: Colors.white),
                                        cursorColor: Colors.white,
                                        decoration: InputDecoration(
                                          border: InputBorder.none,
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                flex: 1,
                              ),
                              Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  _minButton(
                                      ontap: () {
                                        try {
                                          if (hasClickBet) {
                                            return;
                                          }
                                          _textEditingController.text =
                                              '${double.parse(_textEditingController.text) ~/ 2}';
                                        } catch (e) {}
                                      },
                                      child: Text(
                                        '1/2',
                                        style: TextStyle(color: _whiteColor()),
                                      )),
                                  _minButton(
                                      ontap: () {
                                        setState(() {
                                          if (hasClickBet) {
                                            return;
                                          }
                                          _textEditingController.text =
                                              '${double.parse(_textEditingController.text) * 2}';
                                        });
                                      },
                                      child: Text(
                                        '2x',
                                        style: TextStyle(color: _whiteColor()),
                                      ))
                                ],
                              ),
                            ],
                          ),
                        ),
                        flex: 6,
                      ),
                      Expanded(
                        flex: 4,
                        child: GestureDetector(
                          onTap: () async {
                            if (value.userId == '') {
                              Navigator.pushNamed(context, 'LoginPage')
                                  .then((value) {
                                wsConnect(context);
                              });
                              return;
                            }
                            if (value.userId != '') {
                              setState(() {
                                if (!hasClickBet) {
                                  gameBet(value.userId);
                                }
                              });
                              VideoUtil.playVideoByUrl(
                                  "sounds/mines/mines-begin.mp3");

                              for (int i = 0; i <= 24; i++) {
                                _mines[i]['type'] = 0;
                              }
                            }

                            if (hasClickBet && canCommit) {
                              settleGame(value.userId);
                            }
                          },
                          child: Container(
                            height: 80,
                            alignment: Alignment.center,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  '$betText',
                                  style: TextStyle(
                                      color: Utils().whiteColor(),
                                      fontSize: 20),
                                ),
                                Visibility(
                                    visible: hasClickBet,
                                    child: Text(
                                      '$cashOutMoney',
                                      style: TextStyle(
                                          color: Utils().whiteColor(),
                                          fontSize: 12),
                                    ))
                              ],
                            ),
                            margin: EdgeInsets.only(left: 10),
                            decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5.0)),
                              color: betColor,
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 70,
                  margin: EdgeInsets.only(top: 20),
                  child: Row(
                    children: [
                      _selectButton(
                          ontap: () {
                            setState(() {
                              _bombsNum = 1;
                              Map pre = {
                                'userId': value.userId,
                                'gameType': 'MINES',
                                'minesCount': _bombsNum
                              };
                              sendMsg('game_pre', pre);
                            });
                            initGameConfig(_bombsNum);
                          },
                          number: '1',
                          isSelect: _bombsNum == 1),
                      _selectButton(
                          ontap: () {
                            setState(() {
                              _bombsNum = 2;
                              Map pre = {
                                'userId': value.userId,
                                'gameType': 'MINES',
                                'minesCount': _bombsNum
                              };
                              sendMsg('game_pre', pre);
                            });
                            initGameConfig(_bombsNum);
                          },
                          number: '2',
                          isSelect: _bombsNum == 2,
                          margin: EdgeInsets.only(left: 4)),
                      _selectButton(
                          ontap: () {
                            setState(() {
                              _bombsNum = 3;
                              Map pre = {
                                'userId': value.userId,
                                'gameType': 'MINES',
                                'minesCount': _bombsNum
                              };
                              sendMsg('game_pre', pre);
                            });
                            initGameConfig(_bombsNum);
                          },
                          number: '3',
                          isSelect: _bombsNum == 3,
                          margin: EdgeInsets.only(left: 4)),
                      _selectButton(
                          ontap: () {
                            setState(() {
                              _bombsNum = 4;
                              Map pre = {
                                'userId': value.userId,
                                'gameType': 'MINES',
                                'minesCount': _bombsNum
                              };
                              sendMsg('game_pre', pre);
                            });
                            initGameConfig(_bombsNum);
                          },
                          number: '4',
                          isSelect: _bombsNum == 4,
                          margin: EdgeInsets.only(left: 4)),
                      _selectButton(
                          number: _bombsNum <= 4 ? 'Mines' : '$_bombsNum',
                          margin: EdgeInsets.only(left: 4),
                          isSelect: _bombsNum > 4,
                          ontap: () {
                            if (value.userId == '') {
                              Navigator.pushNamed(context, 'LoginPage')
                                  .then((value) {
                                wsConnect(context);
                              });
                              return;
                            }
                            _showBasicModalBottomSheet(context, ontap: (e) {
                              setState(() {
                                _bombsNum = e;
                                //选择新的炸弹数量时需要更新redis的值
                                Map pre = {
                                  'userId': value.userId,
                                  'gameType': 'MINES',
                                  'minesCount': e
                                };
                                sendMsg('game_pre', pre);
                              });
                              initGameConfig(_bombsNum);
                              Navigator.pop(context);
                            });
                          }),
                    ],
                  ),
                ),
                TabBar(
                  controller: _tabController,
                  tabs: _tabs.map((e) => Tab(text: e)).toList(),
                  onTap: (i) {
                    setState(() {
                      _fIndex = i;
                    });
                  },
                ),
                _fIndex == 1 ? GamesAuto() : Container(),
                TabBar(
                  indicator: const UnderlineTabIndicator(
                      borderSide: BorderSide(width: 2.0, color: Colors.red)),
                  controller: _tabController2,
                  tabs: _tabs2.map((e) => Tab(text: e)).toList(),
                  onTap: (i) {
                    setState(() {
                      _fIndex2 = i;
                    });
                  },
                ),
                VipRectangleBox(
                  color: Color(0xFF291F62),
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: _tableList(_fIndex2),
                  ),
                ),
              ],
            ),
          );
        }));
  }

  _initGameData() {
    setState(() {
      for (var i = 0; i < 25; i++) {
        _mines.add({'data': 0});
      }
    });
  }

  // hits
  Widget _hit({String? text, String? text2, bool? isSelect}) {
    return Container(
      // width: 80,
      padding: EdgeInsets.only(left: 14, right: 14),
      margin: EdgeInsets.only(left: 12),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
        color: isSelect == null || isSelect == false
            ? Color(0xFF453C7C)
            : Color(0xFF7A50F0),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            text == null ? '1.5x' : text + 'x',
            style: TextStyle(color: Color(0xFFFFFFFF), fontSize: 10),
          ),
          Text(
            text2 == null ? '13 Hits' : text2 + " Hits",
            style: TextStyle(color: Color(0xFFFFFFFF), fontSize: 10),
          ),
        ],
      ),
    );
  }

// 选择按钮
  Widget _selectButton(
      {String? number,
      bool? isSelect,
      EdgeInsets? margin,
      double? width,
      Function? ontap}) {
    return GestureDetector(
      onTap: () {
        if (!hasClickBet) {
          if (ontap != null) {
            ontap();
          }
        }
      },
      child: Container(
          height: 70,
          width: width ?? (Utils().getScreenWidth(context) - 60) / 5,
          margin: margin,
          alignment: Alignment.center,
          child: Text(
            '${number ?? ''}',
            style: TextStyle(color: Utils().whiteColor(), fontSize: 20),
          ),
          decoration: BoxDecoration(
              border: _loutLine(),
              color: isSelect == null || isSelect == false
                  ? Color(0xFF221B50)
                  : Color(0xFF7A50F0),
              borderRadius: BorderRadius.all(Radius.circular(5.0)))),
    );
  }

  Widget _gameDatas(type) {
    if (type == 1) {
      return _bomb();
    }
    if (type == 2) {
      return _coin();
    }
    if (type == 3) {
      return _coinRoll();
    }
    if (type == 4) {
      return _coinUnRoll();
    }
    if (type == 5) {
      return _bombRoll();
    }

    return _unknown();
  }

// 问号
  Widget _unknown() {
    return Container(
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Color(0xFF236FE2),
        boxShadow: [
          BoxShadow(
              color: Color(0xFF1D4B90),
              offset: Offset(0.0, 2.0),
              blurRadius: 1,
              spreadRadius: 1)
        ],
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
      ),
      child: Image.asset(
        'images/games/mines/unknown-icon.png',
        fit: BoxFit.fill,
        width: 12,
      ),
    );
  }

  Widget _coin() {
    return Container(
      decoration: BoxDecoration(
        color: Color(0xFF1B203F),
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
      ),
      alignment: Alignment.center,
      child: Image.asset(
        'images/games/mines/coin.png',
        fit: BoxFit.fill,
        width: 25,
      ),
    );
  }

  Widget _coinRoll() {
    return Container(
      decoration: BoxDecoration(
        // color: Color(0xFF1B203F),
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
      ),
      alignment: Alignment.center,
      child: Image.asset(
        'images/games/mines/coinRoll.png',
        fit: BoxFit.fill,
        width: 60,
      ),
    );
  }

  Widget _coinUnRoll() {
    return Container(
      decoration: BoxDecoration(
        // color: Color(0xFF1B203F),
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
      ),
      alignment: Alignment.center,
      child: Image.asset(
        'images/games/mines/coinUnroll.png',
        fit: BoxFit.fill,
        width: 60,
      ),
    );
  }

  Widget _bomb() {
    return Container(
      decoration: BoxDecoration(
        color: Color(0xFF1B203F),
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
      ),
      alignment: Alignment.center,
      child: Image.asset(
        'images/games/mines/bombUnroll.png',
        fit: BoxFit.fill,
        width: 60,
      ),
    );
  }

  Widget _bombRoll() {
    return Container(
      decoration: BoxDecoration(
        // color: Color(0xFF1B203F),
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
      ),
      alignment: Alignment.center,
      child: Image.asset(
        'images/games/mines/bombRoll.png',
        width: 60,
      ),
    );
  }

  // 边框的container
  Border _loutLine() {
    return Border.all(width: 1, color: Color.fromRGBO(255, 255, 255, 0.5));
  }

  Widget _minButton({Widget? child, EdgeInsets? margin, Function? ontap}) {
    return GestureDetector(
      onTap: () {
        if (ontap != null) {
          ontap();
        }
      },
      child: Container(
        margin: margin,
        decoration: BoxDecoration(
          color: Color(0xFF413497),
          borderRadius: const BorderRadius.all(Radius.circular(4.0)),
        ),
        padding: EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 4),
        child: child,
      ),
    );
  }

  // 白色
  Color _whiteColor() {
    return Color(0xFFFFFFFF);
  }

  _showBasicModalBottomSheet(context, {Function? ontap}) {
    List numbers = [];
    for (var i = 1; i <= 24; i++) {
      numbers.add(i);
    }
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return ListView(
          padding: EdgeInsets.only(left: 10, right: 10),
          children: numbers
              .map((e) => GestureDetector(
                    onTap: () {
                      if (ontap != null) {
                        ontap(e);
                      }
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(
                              width: 1, color: Color.fromRGBO(0, 0, 0, 0.06)),
                        ),
                      ),
                      alignment: Alignment.center,
                      width: Utils().getScreenWidth(context),
                      padding: EdgeInsets.all(20),
                      child: Text(
                        '$e',
                        style: TextStyle(
                            fontWeight: FontWeight.w700, fontSize: 16),
                      ),
                    ),
                  ))
              .toList(),
        );
      },
    );
  }

  _showChargeAlert(errorMsg) {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Tips"),
            content: Text("$errorMsg"),
            actions: <Widget>[
              TextButton(
                child: Text("Cancel"),
                onPressed: () => Navigator.of(context).pop(),
              ),
              TextButton(
                child: Text("Deposit"),
                onPressed: () {
                  // 跳转到充值页面
                  Navigator.of(context).pop(true); //关闭对话框
                },
              ),
            ],
          );
        });
  }

  _showDialog(bool isLose, {String? subTitle, String? imgSrc}) {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 250,
                height: 150,
                decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                    gradient: LinearGradient(
                      colors: [
                        isLose ? Color(0xFFFF3F61) : Color(0xFFB275FF),
                        isLose ? Color(0xFFFF855F) : Color(0xFF5F82FF),
                      ],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    )),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    imgSrc != null
                        ? Image.asset(
                            imgSrc,
                            width: 60,
                          )
                        : Container(),
                    Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Text(
                        subTitle ?? '',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.w700),
                      ),
                    ),
                  ],
                ),
              )
            ],
          );
        });
    Future.delayed(Duration(seconds: 1), () {
      Navigator.of(context).pop();
    });
  }

  Widget _tableList(index) {
    if (index == 1) {
      return DataTable(
        columns: _playerHeader.map((e) {
          return DataColumn(
            label: Text(
              '$e',
              style: TextStyle(color: Colors.white38),
            ),
          );
        }).toList(),
        rows: _createTableRow(_playerData, ['player', 'cashOut', 'bets']),
      );
    }
    return DataTable(
      columns: _myBetHeader.map((e) {
        return DataColumn(
          label: Text(
            '$e',
            style: TextStyle(color: Colors.white38),
          ),
        );
      }).toList(),
      rows: _createTableRow(
          _myBetData, ['betId', 'time', 'bet', 'cashOut', 'profit']),
    );
  }

  List<DataRow> _createTableRow(List<Map> data, List<String> keys) {
    return data.map((e) => DataRow(cells: _createTableCell(e, keys))).toList();
  }

  List<DataCell> _createTableCell(Map data, List<String> keys) {
    return keys.map((e) {
      if (['bet', 'profit', 'bets'].contains(e)) {
        return DataCell(
          Row(
            children: [
              Text(
                'R\$ ',
                style: TextStyle(color: Color(0xFFFFED4A)),
              ),
              Text(
                '${data[e]}',
                style: TextStyle(color: Colors.white),
              ),
            ],
          ),
        );
      }
      if (['cashOut', 'result'].contains(e)) {
        if (e == 'cashOut') {
          Color color = Colors.green;
          if (data['profit'] == '0.00' || data['win'] == false) {
            color = Colors.red;
          }
          return DataCell(
            Container(
              width: 50,
              height: 20,
              decoration: BoxDecoration(
                color: color,
                borderRadius: BorderRadius.all(Radius.circular(3.0)),
              ),
              alignment: Alignment.center,
              child: Text(
                '${data[e]}',
                style: TextStyle(color: Colors.white),
              ),
            ),
          );
        }
      }
      return DataCell(Text(
        '${data[e]}',
        style: TextStyle(color: Colors.white60),
      ));
    }).toList();
  }

  getMyBets() async {
    //当前时间倒推1个月
    var now = DateTime.now();
    DateTime newMonth = DateTime(now.year, now.month - 1, now.day);
    String endDate = DateFormat("yyyy-MM-dd").format(now);
    String startDate = DateFormat("yyyy-MM-dd").format(newMonth);

    Map param = {
      'gameType': 'MINES',
      'startDate': startDate,
      'endDate': endDate,
      'limit': 20,
      'pageSize': 10
    };
    try {
      dynamic result = await Api.historyInfo(param);
      List tempData = result['data'];
      _myBetData = [];
      if (tempData.length > 0) {
        for (int i = 0; i < tempData.length; i++) {
          _myBetData.add({
            'betId': tempData[i]['recordNo'],
            'time': tempData[i]['playTime'],
            'bet': tempData[i]['betAmount'],
            'cashOut': tempData[i]['payOut'].toStringAsFixed(2) + 'x',
            'profit': tempData[i]['winAmount'].toStringAsFixed(2)
          });
        }
        setState(() {});
      }
    } catch (e) {}
  }

  //点击小的方格的时候
  gameStart(prediction, userId) {
    Map gameStart = {
      'amount': double.parse(_textEditingController.text),
      'gameType': 'MINES',
      'isfast': false,
      'minesCount': _bombsNum,
      'prediction': prediction,
      'type': 'GAME_MINI_SETTLE',
      'userId': userId
    };
    sendMsg("game_start", gameStart);
  }

  gameBet(userId) {
    setState(() {
      if (hitCount != 0) {
        _hitList[hitCount - 1]['isSelect'] = false;
        hitCount = 0;
      }
    });
    Map gameBetParam = {
      'amount': _textEditingController.text,
      'gameType': 'MINES',
      'isfast': false,
      'minesCount': _bombsNum,
      'type': 'GAME_BET',
      'userId': userId
    };
    sendMsg("game_bet", gameBetParam);
  }

  settleGame(userId) {
    Map gameStart = {
      'amount': _textEditingController.text,
      'gameType': 'MINES',
      'isfast': false,
      'minesCount': _bombsNum,
      'type': 'GAME_SETTLE',
      'userId': userId
    };
    sendMsg("game_start", gameStart);
    settle = true;
  }

  changeBetToCashOut() {
    setState(() {
      betText = "CASHOUT";
      betColor = Color(0xffFF8096);
      cashOutMoney = _textEditingController.text;
    });
  }

  getMyBetsAndAccount() {
    String? userId = context.read<UserModel>().userId;
    if (userId != '') {
      Account.refreshAccount(context);
      Future.delayed(Duration(milliseconds: 1), (() {
        getMyBets();
      }));
      setState(() {});
    }
    String accountAmount = context.read<UserModel>().accountAmount;
    if (accountAmount != '') {
      _accountAmountController =
          AnimatedDigitController(double.parse(accountAmount));
    } else {
      _accountAmountController = AnimatedDigitController(0.00);
    }
  }

  _circleMoney({double? width, String? money}) {
    return Row(
      children: [
        Container(
          width: width,
          margin: EdgeInsets.only(left: 12),
          padding: EdgeInsets.only(top: 4, bottom: 4, left: 8, right: 8),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(20.0)),
              border: Border.all(color: Color(0xFF9C4EFF), width: 1)),
          child: Row(
            children: [
              Container(
                width: 24,
                height: 24,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xFF9174FB),
                    borderRadius: BorderRadius.all(Radius.circular(12.0))),
                child: Text(
                  "R\$",
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.white,
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(left: 5),
                child: AnimatedDigitWidget(
                  value: _accountAmountController.value,
                  textStyle: TextStyle(color: Colors.white, fontSize: 10),
                  fractionDigits: 2,
                  enableDigitSplit: true,
                  digitSplitSymbol: ",",
                ),
              )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 20),
          child: GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, 'WithdrawnPage');
            },
            child: Image.asset(
              'images/wallet-app-bar.png',
              width: 24,
            ),
          ),
        )
      ],
    );
  }
}
